package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ProductDto;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.form.CartForm;
import com.cskaoyan.shopping.form.PageInfo;
import com.cskaoyan.shopping.service.ICartService;
import com.cskaoyan.shopping.service.IContentService;
import com.cskaoyan.shopping.service.IProductService;
import com.cskaoyan.shopping.service.impl.IProductServiceImpl;
import com.cskaoyan.user.constants.UserRetCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品接口
 *
 * @author D_y_Y
 * @since 2022/06/18 11:14
 */
@RestController
public class ShopGoodsController {
    @Autowired
    IProductServiceImpl productService;

    @Autowired
    IContentService contentService;

    @Autowired
    ICartService cartService;

    /**
     * 全部商品接口
     * TODO：整合rides
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/18 14:56
     */
    @GetMapping("/shopping/goods")
    public ResponseData shopGoods(PageInfo pageInfo) {

        AllProductRequest request = new AllProductRequest();
        request.setSort(pageInfo.getSort());
        request.setSize(pageInfo.getSize());
        request.setPriceLte(pageInfo.getPriceLte());
        request.setCid(pageInfo.getCid());
        request.setPriceGt(pageInfo.getPriceGt());
        request.setPage(pageInfo.getPage());
        AllProductResponse allProduct = productService.getAllProduct(request);
        if("1".equals(pageInfo.getSort())){
            //价格从低到高
            List<ProductDto> productDtos = new LinkedList<>();
            productDtos =  allProduct.getData().stream().sorted(Comparator.comparing(ProductDto::getSalePrice)).collect(Collectors.toList());
            allProduct.setData(productDtos);
            if (allProduct.getCode().equals(UserRetCode.SUCCESS.getCode())) {
                return new ResponseUtil().setData(allProduct);
            }
            return new ResponseUtil().setData(allProduct.getMsg());
        }else if("-1".equals(pageInfo.getSort())){
            //价格从高到低
            List<ProductDto> productDtos = new LinkedList<>();
            productDtos =allProduct.getData().stream().sorted(Comparator.comparing(ProductDto::getSalePrice).reversed()).collect(Collectors.toList());
            allProduct.setData(productDtos);
            if (allProduct.getCode().equals(UserRetCode.SUCCESS.getCode())) {

                return new ResponseUtil().setData(allProduct);
            }
            return new ResponseUtil().setData(allProduct.getMsg());
        }

        if (allProduct.getCode().equals(UserRetCode.SUCCESS.getCode())) {

            return new ResponseUtil().setData(allProduct);
        }
        return new ResponseUtil().setData(allProduct.getMsg());
    }

    /**
     * 推荐商品
     * TODO:代码格式修改/返回值判断
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/18 15:24
     */

    @GetMapping("/shopping/recommend")
    public ResponseData shopRecommend() {
        RecommendResponse response = productService.getRecommendGoods();

           if(response.getCode().equals(UserRetCode.SUCCESS.getCode())){

               return new ResponseUtil().setData(response.getPanelContentItemDtos());
           }else {

               return new ResponseUtil().setErrorMsg(response.getMsg());
           }
    }

    /**
     * 商品导航模块
     * TODO:代码格式修改/返回值判断
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/18 16:32
     */
    @GetMapping("/shopping/navigation")
    public ResponseData shopNavigation() {
        NavListResponse response = contentService.queryNavList();
        if(response.getCode().equals(UserRetCode.SUCCESS.getCode())){

            return new ResponseUtil().setData(response.getPannelContentDtos());
        }else {
            return new ResponseUtil().setErrorMsg(response.getMsg());
        }



    }

    /**
     * 获得购物车列表
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/18 18:01
     */

    @GetMapping("/shopping/carts")
    public ResponseData shopCartsGet(HttpServletRequest request) {
        String userInfo = (String) request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();
        cartListByIdRequest.setUserId(uid);
        CartListByIdResponse checkAllItemResponse = cartService.getCartListById(cartListByIdRequest);
        if (checkAllItemResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(checkAllItemResponse.getCartProductDtos());
        }
        return new ResponseUtil().setErrorMsg(checkAllItemResponse.getMsg());
    }

    @PostMapping("/shopping/carts")
    public ResponseData shopCartsPost(HttpServletRequest request, @RequestBody CartForm cartForm) {
        AddCartRequest addCartRequest = new AddCartRequest();
        addCartRequest.setUserId(cartForm.getUserId());
        addCartRequest.setItemId(cartForm.getProductId());
        addCartRequest.setNum(cartForm.getProductNum());
        AddCartResponse addCartResponse = cartService.addToCart(addCartRequest);
        if (addCartResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {

            return new ResponseUtil().setData(null);
        } else {

            return new ResponseUtil().setErrorMsg(addCartResponse.getMsg());
        }

    }







        @PutMapping("/shopping/carts")
        public ResponseData shopCartsPut(@RequestBody CartForm cartForm){
            cartService.updateCartCheck(cartForm);
            return new ResponseUtil().setData(UserRetCode.SUCCESS.getMessage());
        }

    /**
    * @Description:  删除购物车中商品(需要获取购物车中全部信息)
    * @Param: * @param null
    * @return:
    * @Author: Theodore
    * @Date: 2022/6/18 20:11
    */
    @DeleteMapping("/shopping/carts/{uid}/{pid}")
    public ResponseData delete(@PathVariable("uid") Long userId,@PathVariable("pid") Long pid){

        DeleteCartItemRequest request = new DeleteCartItemRequest();
        request.setUserId(userId);
        request.setItemId(pid);
        DeleteCartItemResponse response = cartService.deleteCartItem(request);


        if (ShoppingRetCode.SUCCESS.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setData("成功","success");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());


    }


    /**
    * @Description: 删除选中商品
    * @Param: * @param null
    * @return:
    * @Author: Theodore
    * @Date: 2022/6/18 20:38
    */

    @DeleteMapping("/shopping/items/{uid}")
    public ResponseData deleteCartSelective (@PathVariable Long uid){
        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();
        request.setUserId(uid);
        DeleteCheckedItemResposne resposne = cartService.deleteCheckedItem(request);
        if (resposne.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setData(resposne.getMsg());
        }
        return new ResponseUtil().setErrorMsg(resposne.getMsg());
    }




    @PutMapping("/shopping/items")
    public ResponseData items(@RequestBody CartForm cartForm){

        CheckAllItemRequest request = new CheckAllItemRequest();
        request.setUserId(cartForm.getUserId());
        request.setChecked(cartForm.getChecked());

        CheckAllItemResponse response = cartService.checkAllCartItem(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setData("成功","success");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());


    }


}
